package com.wish.nettyprotocol.client;

import com.wish.nettyprotocol.common.MessageType;
import com.wish.nettyprotocol.struct.Header;
import com.wish.nettyprotocol.struct.NettyMessage;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;

import java.util.Date;
import java.util.Random;

/**
 * @author tantexian
 * @since 2016/7/21
 */
public class RandomSentHandler extends ChannelHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        NettyMessage message = (NettyMessage) msg;
        System.out.println("RandomSentHandler channelRead : " + message);
        final ChannelHandlerContext CTX = ctx;
        // 如果是oneway消息，则随机间隔时间，发送当前时间给服务器端
        //        if (message.getHeader() != null && message.getHeader().getType() == MessageType.ONE_WAY.value()) {
        //            Byte loginResult = (Byte) message.getBody();
        //            System.out.println("[edit by ttx]message.getBody() == " + loginResult);
        //            if (loginResult != (byte) 0) {
        //                // 握手失败，关闭连接
        //                ctx.close();
        //            } else {
        //                System.out.println("Login is ok : " + message);
        //                ctx.fireChannelRead(msg);
        //            }
        //        } else {
        //            ctx.fireChannelRead(msg);
        //        }
        new Thread(new Runnable() {
            public void run() {
                NettyMessage message = new NettyMessage();
                Header header = new Header();
                header.setType(MessageType.ONE_WAY.value());
                message.setHeader(header);
                message.setBody("Now time from client is:" + new Date());
                CTX.writeAndFlush(message);
                System.out.println("RandomSentHandler == " + message);
                try {
                    Thread.sleep(new Random().nextInt(1000));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        super.channelReadComplete(ctx);
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
